import { createRouter, createWebHistory } from "vue-router"; //由宿主提供
import type { Router } from "vue-router";
import { useLayoutStore } from "../stores/layout.js";
import { useMenusStore } from "../stores/menus.js";
import { useAccountStore } from "../stores/account.js";

import SunAdminLayout from "../components/layout/index.vue";
import home from "./home";
import login from "./login";
import maintenance from "./maintenance";

var router:Router;
export const setupRouter = (basePath: string)=>{
    router = createRouter({
        history: createWebHistory(basePath),
        routes: [
            {
                path: "/",
                name: "sunadmin-layout",
                component: SunAdminLayout,
                children: [home, maintenance],
            },
            login,
        ],
    });
    router.beforeEach(async (to, from) => {
        const layoutStore = useLayoutStore();
        const menusStore = useMenusStore();
        const accountStore = useAccountStore();
    
        // console.log("路由导航:", to, from);
        // 添加tag标签
        layoutStore.addTags(to);
    
        // 设置当前激活的菜单
        const pathSegments = to.path.split("/").filter(Boolean);
        const currentLevel1MenuKey = pathSegments.length === 0 ? "/" : `/${pathSegments[0]}`;
        const currentLevel2MenuKey = pathSegments.length >= 2 ? to.path : "";
    
        menusStore.currentLevel1MenuKey = currentLevel1MenuKey;
        menusStore.currentLevel2MenuKey = currentLevel2MenuKey;
    
        // 登录状态检查
        if (!accountStore.isLogin && to.name !== "login") {
            return { name: "login" };
        }
    
        if (accountStore.isLogin && to.name == "login") {
            return { path: "/" };
        }
    });
    return router;
}

export { router };
